﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace FlightSearchServer
{
    [ServiceContract]
    public interface ISearchService
    {
        [OperationContract]
        [WebGet(UriTemplate = "flights?from={from}&to={to}&date={date}&servers={servers}")]
        List<AvailableAirTravel> Search(string from, string to, string date, string[] servers);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    internal class SearchService : ISearchService
    {
        private readonly SearchManager searchManager;

        public SearchService(SearchManager searchManager)
        {
            this.searchManager = searchManager;
        }

        public List<AvailableAirTravel> Search(string from, string to, string date, string[] servers)
        {
            if (WebOperationContext.Current != null)
            {
                try
                {
                    var dt = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.CurrentCulture);

                    var res = searchManager.Search(from, to, dt, servers);

                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;

                    return res;
                }
                catch (FormatException)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                    WebOperationContext.Current.OutgoingResponse.StatusDescription = "Bad date format";
                }
            }

            return null;
        }
    }
}
